<template>
	<view>
		<view class="goods-item" v-for="item in goodsList" :key="item.goods_id" @click="toDetail(item)">
			<!-- 左边图片 -->
			<image class="pic"
				:src="item.goods_small_logo || 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png'">
			</image>
			<!-- 右边的盒子 -->
			<view class="info-box">
				<text class="title">{{ item.goods_name }}</text>
				<text class="price">￥ {{ item.goods_price.toFixed(2) }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		// onLoad有形参，形参里就有传递过来的数据
		onLoad(options) {
			// 把传递过来的参数存起来
			this.params.query = options.query || ''
			this.params.cid = options.cid || ''

			// 调用请求方法
			this.getGoodsList()
		},
		// 触底触发的钩子
		onReachBottom() {
			if (this.isLoading) return
			// 判断是否完成
			if (this.finished) return uni.showToast({
				title: '数据加载完毕',
				icon: 'none'
			})
			// 让页码+1
			this.params.pagenum++
			// 发请求加载数据
			this.getGoodsList()
		},
		// 监听下拉刷新的钩子
		onPullDownRefresh() {
			// 重新加载数据
			this.params.pagenum = 1
			// 数组要清空
			this.goodsList = []
			// 加载状态都变成完成了，所以要恢复
			this.finished = false
			// 发请求加载数据
			this.getGoodsList()
		},
		data() {
			return {
				params: {
					query: '',
					cid: '',
					pagenum: 1,
					pagesize: 10
				},
				goodsList: [],
				// 标记有没有全部加载完毕
				finished: false,
				// 标记当前有没有正在加载
				isLoading: false
			};
		},
		methods: {
			// 每个商品的点击事件
			toDetail(item) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
				})
			},
			// 加载数据的方法
			async getGoodsList() {
				this.isLoading = true
				const res = await uni.$http.get('goods/search', this.params)
				// 每次追加
				this.goodsList.push(...res.data.message.goods)
				// 发完请求就变false
				this.isLoading = false
				// 加载完数据都要判断是否加载完毕
				this.finished = this.goodsList.length >= res.data.message.total
				// 停止下拉状态
				uni.stopPullDownRefresh()
			}
		}
	}
</script>

<style lang="scss">
	.goods-item {
		display: flex;
		margin: 20rpx;

		.pic {
			width: 260rpx;
			height: 260rpx;
			margin-right: 10px;
		}

		.info-box {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.price {
				color: #c00;
			}
		}
	}
</style>
